package templateDesigner

import org.grails.plugins.wsclient.service.WebService
import com.thoughtworks.xstream.XStream

class LayoutService {

    static transactional = true
    WebService webService
    
    def listaLayouts

    def getJerarquiaDetallesArtefacto() {
        
        def wsdlURL = 'http://localhost:8080/ArtefactRepository-OpenEHRGen/services/layout?wsdl'
        def proxy = webService.getClient(wsdlURL)

        def result = proxy.getJerarquiaDetallesArtefacto()      
        return result 
    }
        
    def getLayout(String n, String v, String p) {
        
        def wsdlURL = 'http://localhost:8080/ArtefactRepository-OpenEHRGen/services/layout?wsdl'
        def proxy = webService.getClient(wsdlURL)

        def result = proxy.getLayout(n,v,p)       
        return result 
    }
    
    //--------------------------------------------------------------------------
    
    def getLayouts() {
        //def jerarquia = getJerarquiaDetallesArtefacto()
        
        //def listaDetallesLayout = getDetallesLayoutsRecursivo(jerarquia.detallesArtefacto.value)
        //def listaLayouts = []

        //listaDetallesLayout.each{elem ->
        //    listaLayouts.add(getLayout(elem.nombreArchivo.value, elem.numVersion.value, elem.path.value))
        //}
        
        return listaLayouts 
    }
    
    //--------------------------------------------------------------------------
    
    def cargarLayouts() {
        def jerarquia = getJerarquiaDetallesArtefacto()
        
        def listaDetallesLayout = getDetallesLayoutsRecursivo(jerarquia.detallesArtefacto.value)
        listaLayouts = []

        listaDetallesLayout.each{elem ->
            listaLayouts.add(getLayout(elem.nombreArchivo.value, elem.numVersion.value, elem.path.value))
        }
    }
    
    //--------------------------------------------------------------------------
    
    def getDetallesLayoutsRecursivo(def nda){ // nda es de tipo NodoDetallesArtefacto
        def listaDetallesLayouts = []
        
        nda.detallesArtefactos.value.detallesArtefacto.each{da ->
            listaDetallesLayouts.add(da);
        }

        nda.nodoHijo.value.nodoDetallesArtefacto.each{nodo ->
            def listaDetallesLayoutsRecursivo = getDetallesLayoutsRecursivo(nodo)
            listaDetallesLayoutsRecursivo.each{da ->
                listaDetallesLayouts.add(da);
            }
        }
        
        return listaDetallesLayouts
    }
    
    //--------------------------------------------------------------------------
    
    
    void imprimirObjetoXML(Object o){
        println "-----------------"
        XStream xstream = new XStream();
        String xml = xstream.toXML(o);
        println xml
        println "-----------------"
    }
}
